package es.decloud.webapp.converter;

import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

import es.decloud.model.Usuario;

@FacesConverter("usuario")
public class UsuarioConverter implements Converter {

	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		return getObjectFromUIPickListComponent(component, value);
	}

	public String getAsString(FacesContext context, UIComponent component, Object object) {
		String string;
		if (object == null) {
			string = "";
		}
		else {
			try {
				string = String.valueOf(((Usuario) object).getId());
			}
			catch (ClassCastException cce) {
				throw new ConverterException();
			}
		}
		
		return string;
	}

	@SuppressWarnings("unchecked")
	private Usuario getObjectFromUIPickListComponent(UIComponent component, String value) {
		final DualListModel<Usuario> dualList;
		try {
			dualList = (DualListModel<Usuario>) ((PickList) component).getValue();
			Usuario usuario = getObjectFromList(dualList.getSource(), Integer.valueOf(value));
			if (usuario == null) {
				usuario = getObjectFromList(dualList.getTarget(), Integer.valueOf(value));
			}

			return usuario;
		}
		catch (ClassCastException cce) {
			throw new ConverterException();
		}
		catch (NumberFormatException nfe) {
			throw new ConverterException();
		}
	}

	private Usuario getObjectFromList(final List<?> list, final Integer identifier) {
		for (final Object object : list) {
			final Usuario usuario = (Usuario) object;
			if (usuario.getId().equals(identifier)) {
				return usuario;
			}
		}
		return null;
	}

}
